package font;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class FontTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(()->{
            var frame = new FontFrame();
            frame.setTitle("FontTest");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });
    }
}

class FontFrame extends JFrame {
    public FontFrame() {
        add(new FontComponent());
        pack();
    }
}

class FontComponent extends JComponent {
    private static final int DEFAULT_WIDTH = 300;
    private static final int DEFAULT_HEIGHT = 200;

    @Override
    public void paintComponent(Graphics g) {
        var g2 = (Graphics2D) g;

        String message = "Hello, World!";

        var f = new Font("Serif", Font.BOLD, 36);
        g2.setFont(f);

        // 获取字符串的边界信息
        // getWidth() = 字符串的水平方向宽度
        // getHeight() = 行间间距(leading) + 上坡度(ascent) + 下坡度(descent)
        // 上坡度(ascent) 和 下坡度(descent) 之间的是基线(baseline)
        var context = g2.getFontRenderContext();
        var bounds = f.getStringBounds(message, context);

        // 设置x, y为文本的左上角
        var x = (getWidth() - bounds.getWidth()) / 2;
        var y = (getHeight() - bounds.getHeight()) / 2;

        // 基线是0, getY() = 行间间距(leading) + 上坡度(ascent)，是个负数
        var leadingAscent = -bounds.getY();

        // baseline是基线，baseY是基线对应的y坐标
        var baseY = y + leadingAscent;

        // 文本垂直位置对齐基线
        g2.drawString(message, (int)x, (int)baseY);

        // 绘制基线
        g2.setPaint(Color.LIGHT_GRAY);
        g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY));

        // 绘制文本的边界
        var rect = new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight());
        g2.draw(rect);

    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }
}
